// pages/second/second.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src:"/resources/show_picture.png",//处理中的图片，处理完成后赋给show_src
    show_src:"/resources/show_picture.png",//未处理完成时展示的图片
    imgproheight:0,
    imgprowidth:0,
    imgprosize:0,
    show_imgprosize:0,
    imgheight:0,
    imgwidth:0,
    imgsize:0,
    maxCanvasW:0,
    maxCanvasH:0

  },
  returnButton:function(e){
  /*  wx.navigateBack({
      delta:1
})*/

    let pages = getCurrentPages();   //获取小程序页面栈
    let beforePage = pages[pages.length -2];  //获取上个页面的实例对象
    beforePage.setData({      //直接修改上个页面的数据（可通过这种方式直接传递参数）
        src:"/resources/add_picture.png",
        security:-1
    })
    //beforePage.go_update();   //触发上个页面自定义的go_update方法
    wx.navigateBack({         //返回上一页  
      delta:1
    })

  },
  saveButton:function(e){
    var that=this;
    wx.getImageInfo({
      src: that.data.show_src,//读取本地化以后的图像
      success: function (res) {
        let path = res.path;
        console.log("getimagepath",path)
        wx.saveImageToPhotosAlbum({
          filePath:path,
          success(res) {
            wx.showToast({
            title: '保存图片成功',
          })
        },
        fail: function (err) {
          console.log(err);
          wx.showToast({
            title: '保存图片失败' ,
          }) }
        })
      }
    })
      },
  /*compress(canvas,dimgW,dimgH,filetype,maxsize,quality){
    var that=this;
wx.canvasToTempFilePath({
  canvas,
  destWidth:dimgW,
  destHeight:dimgH,
  fileType:filetype,
  quality:quality,
  success(res){
    let file=res.tempFilePath;
    wx.getFileSystemManager().getFileInfo()({
      filePath:res.tempFilePath,
      
      success(res){
        const filesize=res.data.byteLength/1024;
        if (filesize<=maxsize){
          that.setData({
            src:file//压缩完毕，最终图像给到src
          })
        }
        else{
          compress(canvas,dimgW,dimgH,"jpg",maxsize,quality-0.1);
        }
      }
    })
  }

})
  },*/
  base64tofile:function(imgData){
    return new Promise<string>((resolve, reject) => {
    const fs = wx.getFileSystemManager();
    const filePath = wx.env.USER_DATA_PATH + "/photo.jpg";
    console.log("替换后：",imgData.replace(/^data:image\/\w+;base64,/, ""))
    fs.writeFile({
      filePath,
      data: imgData.replace(/^data:image\/\w+;base64,/, ""),
      encoding: 'base64',
                      
        })
    resolve(filePath)
    })
  },
  getfilesize:function(tempfile){
    return new Promise<number>((resolve, reject) => {
      wx.getFileSystemManager().getFileInfo(
        {
          filePath:tempfile,
            success(res)
          {
            let imagesize=Math.ceil(res.size/1024);
            console.log("getfileinfo ing..此时临时文件大小为",imagesize,"KB")
            resolve(imagesize)
          },
          fail(res){
            console.log("getfileinfo error",res)
          }
        })
    })

  },
  compressimage:function(tempfile,quality){
    return new Promise<string>((resolve, reject) => {
      wx.compressImage({
        src: tempfile, // 图片路径
        quality: quality ,// 压缩质量
        success(res){
          //console.log("缩放又压缩后临时文件地址",res.tempFilePath); // 生成临时文件路径
          resolve(res.tempFilePath)
        }
      });
    })

  },
  save_photo: function () {
    return new Promise<string>((resolve, reject) => {
    const fs = wx.getFileSystemManager()
    var isExist = false; //目录是否存在
    var that = this;
    // 同步接口
    try {
      fs.accessSync(`${wx.env.USER_DATA_PATH}/photo`)
      isExist = true;
    } catch (e) {
       console.error(e)
    }
    if (isExist != true) {
      // 同步接口,创建目录
      try {
        fs.mkdirSync(`${wx.env.USER_DATA_PATH}/photo`, true)
      } catch (e) {
        console.error(e)
      }
    }
     console.log("本地路径为：",`${wx.env.USER_DATA_PATH}/photo`)
     console.log("待保存图片路径为：",that.data.src)
 
 
    wx.getImageInfo({
      src: this.data.src,
      success: function (res) {
        var path = res.path;
        //console.log("path:" + path) //wxfile://te6786958409efjje46546i5.jpg
        //下面获取图片名te6786958409efjje46546i5.jpg
        var startPos = path.lastIndexOf("//");//"//"所在的初始位置
        //console.log(startPos)
        var picName = path.slice(startPos + 2, path.length); //加2是为了从//后面截取。所以+2，把//过滤掉
        console.log("保存后的图片完整路径为：", `${wx.env.USER_DATA_PATH}/photo/${picName}`)
        fs.saveFile({
          tempFilePath: path,
          filePath: `${wx.env.USER_DATA_PATH}/photo/${picName}`, //保存的时候必须跟上路径和文件名
          success: function (res) {
            console.log("保存成功")
            resolve(`${wx.env.USER_DATA_PATH}/photo/${picName}`)
            //console.log(res)
          },
          fail: function (res) {
            console.log("保存失败")
            //console.log(res)
          }
        })
 
      }
    })
    })
  },
  readImage:async function(){//获取图片的宽和高
    var that=this;
    wx.getImageInfo({
      src: this.data.src,
      success: function (e2) {
        const imgW = e2.width;
        const imgH = e2.height;
        var dimgW = that.data.imgprowidth;
        var dimgH = that.data.imgproheight;
        const maxWidth=that.data.maxCanvasW;//设置最大分辨率
        const maxHeight=that.data.maxCanvasH;
        if (dimgW > maxWidth) {
          const ratio = maxWidth / dimgW
          dimgW = maxWidth
          dimgH = dimgH * ratio
      }
      if (dimgH > maxHeight) {
          const ratio = maxHeight / dimgH
          dimgW = dimgW * ratio
          dimgH = maxHeight
      }
        //const dimgH=180*that.data.imgproheight/that.data.imgprowidth;
        //const dimgW=180;
       // const dpr = wx.getSystemInfoSync().pixelRatio*0.1 ;//影响清晰程度
       const dpr = wx.getSystemInfoSync().pixelRatio ;//影响清晰程度
       
        //const dpr=0.6;
        //const imgW = Math.trunc(imgWidth / dpr);
        //const imgH = Math.trunc(imgW / imgWidth * imgHeight);
        //const imgW = imgWidth ;
        //const imgH = imgHeight ;
        
        that.setData({//获取原图宽，高
          imgheight:e2.height,
          imgwidth:e2.width
        })
        const query = wx.createSelectorQuery();
        query.select('#avatarCanvas').fields({
              node: true,
              size: true
            }).exec(e3 => {
              console.log('获取画布：', e3);
              const canvas = e3[0].node;
              canvas.width=dimgW*dpr;
              canvas.height=dimgH*dpr;
              
              console.log("imgW,imgH:",imgW,imgH);
              console.log("dimgW,dimgH:",dimgW,dimgH);
              console.log("canvasW,canvasH:",canvas.width,canvas.height);
              
              const ctx = canvas.getContext('2d');
              //ctx.scale(dpr*dimgW/imgW,dpr*dimgW/imgW*(dimgH/dimgW));//按比例缩放
              //ctx.scale(dpr*dimgW/imgW,dpr*dimgH/imgH);//按比例缩放
              ctx.scale(dpr,dpr);//按比例缩放
             // console.log("dprw,dprh:",dimgW/imgW,dimgH/imgH);
              ctx.clearRect(0, 0, dimgW,dimgH);//清空画布



              //离线画布
             /* const offcanvas = wx.createOffscreenCanvas({ type: '2d', width: dimgW, height: dimgH })
              offcanvas.width=dimgW;
              offcanvas.height=dimgH;
              const offctx = offcanvas.getContext('2d');*/
             // offctx.scale(dpr,dpr);//按比例缩放
              //console.log("dprw,dprh:",dimgW/imgW,dimgH/imgH);
             // offctx.clearRect(0, 0, dimgW,dimgH);//清空画布
              //***************** */


              const img = canvas.createImage();//使用在线画布新建图像
              //const img = offcanvas.createImage();//使用离线画布新建图像
              //const fileManager = wx.getFileSystemManager()
              //const base64 = "data:image/jpg;base64,"+fileManager.readFileSync(that.data.src, 'base64');
             //const fileManager = wx.getFileSystemManager()
             //const base64 = fileManager.readFileSync(that.data.src, 'base64');
              //img.src = base64;

              img.src=that.data.src;
             // img.width=that.data.imgwidth;
             // img.height=that.data.imgheight;
              console.log("原图地址为",that.data.src)
              console.log("待加载图片为",img)
              //console.log("图片base64码",base64)
              /*that.setData({
                show_src:img.src
              })*/ 
              img.onload = async () => 
              {
                console.log('原图已加载完成，下一步将原图绘制在画布上');
                /*
                await offctx.drawImage(img, 0, 0,dimgW,dimgH);//将原图绘制在离线画布上
                
                
                let tempfile=await that.base64tofile(offcanvas.toDataURL());//原图
                console.log("绘制已完成",tempfile)
                console.log("base64转化为临时文件：",tempfile)
                let tempfile1=tempfile;//压缩后的图，初始化为原图
                let imagesize=await that.getfilesize(tempfile1)//初次测量原图
                console.log("要求文件大小为",that.data.imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                let times=95
                while (imagesize >that.data.imgprosize && times>0){
                  //let isGetinfo=false;
                 // if (times==0) break;
                  console.log("quality:",times)
                  tempfile1=await that.compressimage(tempfile,times);
                  imagesize=await that.getfilesize(tempfile1)
                  times-=5
                }
                if (imagesize >that.data.imgprosize){
                  console.log("我们已经尽力啦！只能压缩到这个程度啦！o(╥﹏╥)o")
                  setTimeout(() => {
                    wx.showToast({
                      title: '我们已经尽力啦！只能压缩到这个程度啦！o(╥﹏╥)o' ,
                    })
                  }, 2000);
                 
                }
                console.log("最终图像地址为:",tempfile1)
                that.setData({
                  src:tempfile1,//处理后的图
                  show_src:tempfile1,//用于展示的处理后的图
                  show_imgprosize:imagesize//展示处理后图的大小
                })
                /*
                /*that.setData({
                  show_src:offcanvas.toDataURL()
                })*/
                //ctx.drawImage(img, 0, 0,imgW,imgH,0, 0,dimgW,dimgH);//将原图绘制在在线画布上
               ctx.drawImage(img, 0, 0,dimgW,dimgH);//将原图绘制在画布上
               //ctx.setFillStyle('red')
               //ctx.fillRect(10, 10, 150, 75)
                await new Promise(resolve => {
                  setTimeout(() => resolve(""), 50);
                });
                /***************************** */
                /*ctx.draw(false,
                  async()=>{
                    setTimeout(() => {
                      wx.canvasToTempFilePath({
                        canvas,
                        x: 0,
                        y: 0,
                        destWidth: that.data.imgprowidth,
                        destHeight: that.data.imgproheight,
                        success(res) {
                          that.setData({
                            src:res.tempFilePath
                          })
                          console.log(res.tempFilePath)
                        },
                        fail(err){
                          console.log(err,'这是报错的');
                        }
                      })
                    }, 100);
                  })*/

                /******************************** */
                
                wx.canvasToTempFilePath({
                  //offcanvas,//使用离线画布的内容保存临时文件
                  canvas,
                  x: 0,
                  y: 0,
                  destWidth: dimgW,
                  destHeight: dimgH,
                  fileType:"jpg",
                  quality:1,
                  async success(res) 
                  {
                         
                         //console.log("缩放后临时文件地址：",res.tempFilePath); 
                         let tempfile=res.tempFilePath;//原图
                         let tempfile1=tempfile;//压缩后的图，初始化为原图
                         let imagesize=await that.getfilesize(tempfile1)//初次测量原图
                        // let isGetinfo=false;
                        /*
                         that.setData({
                          show_src:res.tempFilePath
                        })*/
                        //setTimeout(()=>{console.log("延时中")},5000);
                        // compress(canvas,dimgW,dimgH,"jpg",that.data.imgprosize,1);
                         //生成临时文件路径
                        /*
                        wx.getFileSystemManager().getFileInfo(
                        {
                          filePath:tempfile,
                            success(res)
                          {
                            console.log("重中之重重中之重")
                            isGetinfo=true;
                          imagesize=res.size/1024;
                          console.log("缩放后临时文件大小为 KB",imagesize)
                          },
                          fail(res){
                            console.log("fail:",res)
                          }
                        })
                        console.log("isGetinfo:",isGetinfo)
                        */
                        
                        console.log("要求文件大小为",that.data.imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                        let times=99
                        while (imagesize >that.data.imgprosize && times>0){
                          //let isGetinfo=false;
                          //if (times==0) break;
                          console.log("第",100-times,"次压缩:")
                          
                          tempfile1=await that.compressimage(tempfile,times);
                          times-=1
                          /*
                          wx.compressImage({
                            src: tempfile, // 图片路径
                            quality: 50 ,// 压缩质量
                            success(res){
                              //console.log("缩放又压缩后临时文件地址",res.tempFilePath); // 生成临时文件路径
                              tempfile=res.tempFilePath
                            }
                          });
                          */
                          imagesize=await that.getfilesize(tempfile1)
                          
                          /*
                          wx.getFileSystemManager().getFileInfo({
                            filePath:tempfile,
                            success(res){
                             // isGetinfo=true;
                              imagesize=res.size/1024;
                              console.log("此时文件大小为 KB",imagesize)
                              console.log("要求文件大小为 KB",that.data.imgprosize)
                            }
                          });*/
                         // console.log("isGetinfo:",isGetinfo)
                          
                          }
                          if (imagesize >that.data.imgprosize){
                            console.log("我们已经尽力啦！只能压缩到这个程度啦！o(╥﹏╥)o")
                            wx.showToast({
                              title: '我们已经尽力啦！只能压缩到这个程度啦！o(╥﹏╥)o' ,
                            })
                          }
                          /*
                          const fileManager = wx.getFileSystemManager()
                          const base64 = "data:image/jpg;base64,"+fileManager.readFileSync(tempfile1, 'base64');
                          console.log("base64为",base64)*/
                        console.log("最终图像地址为:",tempfile1)
                        that.setData({
                          src:tempfile1,//处理后的图
                          show_src:tempfile1,//用于展示的处理后的图
                        })
                        //let localpath=await that.save_photo();//将处理后的图本地化
                       // console.log("保存到本地的图像地址为:",localpath)
                        that.setData({//将最终结果进行展示
                          //src:localpath,//处理后的图
                         // show_src:localpath,//展示处理后的本地的图
                          //src:tempfile1,//处理后的图
                          //show_src:tempfile1,//展示处理后的图
                          //src:base64,//处理后的图
                          //show_src:base64,//展示处理后的图
                          show_imgprosize:imagesize//展示处理后图的大小
                      })
                        }
                      })
                        /* wx.compressImage({
                          src: res.tempFilePath, // 图片路径
                          quality: 99 ,// 压缩质量
                          success(res){
                            console.log("缩放又压缩后临时文件地址：",res.tempFilePath); // 生成临时文件路径
                            that.setData({
                              src:res.tempFilePath
                            })

                          }
                        })*/
                        
                   }
                })
              }
              

            });
      },
      fail: function (res) {
        console.log(res.errMsg)
      },
    
   
  
  
  resizeImage: async function(){
  
   },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    this.setData({
      src:options.imgsrc,
      //src:wx.getStorageSync('key'),
      //show_src:wx.getStorageSync('key'),
      imgproheight:Number(options.imgproheight),
      imgprowidth:Number(options.imgprowidth),
      imgprosize:Number(options.imgprosize),
      imgsize:Number(options.imgsize),
      maxCanvasW:Number(options.maxCanvasW),
      maxCanvasH:Number(options.maxCanvasH),
    })
    this.readImage()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})